package com.ruoyi.dynamic.controller;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisUtil;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.date.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dynamic.domain.UserDynamic;
import com.ruoyi.dynamic.domain.UserDynamicAuto;
import com.ruoyi.dynamic.mapper.UserDynamicAutoMapper;
import com.ruoyi.dynamic.service.IUserDynamicService;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 用户发布动态/活动Controller
 * 
 * @author DEREK
 * @date 2023-08-08
 */
@RestController
@RequestMapping("/dynamic/dynamic")
public class UserDynamicController extends BaseController
{
    @Autowired
    private IUserDynamicService userDynamicService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 查询用户发布动态/活动列表
     */
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserDynamic userDynamic)
    {
        startPage();
        List<UserDynamic> list = userDynamicService.selectUserDynamicList(userDynamic);
        return getDataTable(list);
    }

    /**
     * 导出用户发布动态/活动列表
     */
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:export')")
    @Log(title = "用户发布动态/活动", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserDynamic userDynamic)
    {
        List<UserDynamic> list = userDynamicService.selectUserDynamicList(userDynamic);
        ExcelUtil<UserDynamic> util = new ExcelUtil<UserDynamic>(UserDynamic.class);
        util.exportExcel(response, list, "用户发布动态/活动数据");
    }

    /**
     * 获取用户发布动态/活动详细信息
     */
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
    	UserDynamic byId = userDynamicService.getById(id);
    	if(StringUtils.isNotEmpty(byId.getImg())) {
    		String[] split = byId.getImg().split(",");
    		byId.setSimpleSpectrum1(Arrays.asList(split));
    	}
        return AjaxResult.success(byId);
    }

    /**
     * 新增用户发布动态/活动
     */
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:add')")
    @Log(title = "用户发布动态/活动", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserDynamic userDynamic)
    {
    	if(userDynamic.getRegular() > 0) {
    		String key = userDynamic.getId()+"-1-"+userDynamic.getRegular();
    		Date pastDateTime = DateUtils.getPastDateTime(userDynamic.getRegular(), userDynamic.getCreateTime(), 2);
    		long expireTime = DateUtils.getDaySecond(userDynamic.getCreateTime(), pastDateTime);
    		redisUtil.set(key, key, expireTime);
    	}
        return toAjax(userDynamicService.save(userDynamic));
    }

    /**
     * 修改用户发布动态/活动
     */
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:edit')")
    @Log(title = "用户发布动态/活动", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserDynamic userDynamic)
    {
    	UserDynamic dynamic = userDynamicService.getOne(new LambdaQueryWrapper<UserDynamic>().eq(UserDynamic::getId, userDynamic.getId())
    			.select(UserDynamic::getId,UserDynamic::getRegular));
    	if(null == dynamic) {
    		return AjaxResult.error("动态不存在");
    	}
    	if(CollectionUtil.isNotEmpty(userDynamic.getSimpleSpectrum1())) {
    		userDynamic.setImg(userDynamic.getSimpleSpectrum1().stream().map(String::valueOf).collect(Collectors.joining(",")));
    	}
    	userDynamic.setAdoptUser("后台更改,更新时间："+DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss")+"，需要修改的状态："+userDynamic.getStatus());
    	userDynamic.setCreateTime(new Date());
    	// 删除定时
//		String delKey = userDynamic.getId()+"-1-"+dynamic.getRegular();
//		if(redisUtil.hasKey(delKey)) {
//			redisUtil.del(delKey);
//		}
//    	if(userDynamic.getRegular() > 0) {
//    		String key = userDynamic.getId()+"-1-"+userDynamic.getRegular();
//    		Date pastDateTime = DateUtils.getPastDateTime(userDynamic.getRegular(), userDynamic.getCreateTime(), 2);
//    		long expireTime = DateUtils.getDaySecond(userDynamic.getCreateTime(), pastDateTime);
//    		redisUtil.set(key, key, expireTime);
//    	}
    	boolean updateById = userDynamicService.updateById(userDynamic);
        return toAjax(updateById);
    }

    /**
     * 删除用户发布动态/活动
     */
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:remove')")
    @Log(title = "用户发布动态/活动", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userDynamicService.deleteUserDynamicByIds(ids));
    }
    
    @Autowired
    private UserDynamicAutoMapper userDynamicAutoMapper;
    
    @PreAuthorize("@ss.hasPermi('dynamic:dynamic:edit')")
	 @Log(title = "将动态加入自动发布列表", businessType = BusinessType.UPDATE)
	 @GetMapping("/joinDynamicAuto")
	 public AjaxResult joinDynamicAuto(Long dynamicId,Long userId)
	 {
    	UserDynamicAuto auto = userDynamicAutoMapper.selectOne(new LambdaQueryWrapper<UserDynamicAuto>()
    			.eq(UserDynamicAuto::getUserId, userId)
    			.eq(UserDynamicAuto::getType, 1).last("limit 1"));
    	if(null != auto) {
    		if(auto.getObjId().contains(dynamicId.toString())) {
    			return AjaxResult.error("当前动态已经加入动态库");
    		}else {
    			if(StringUtils.isNotEmpty(auto.getObjId())) {
    				auto.setObjId(auto.getObjId()+","+dynamicId);
    			}else {
    				auto.setObjId(String.valueOf(dynamicId));
    			}
    		}
    		userDynamicAutoMapper.updateById(auto);
    	}else {
    		auto = new UserDynamicAuto();
    		auto.setUserId(userId);
    		auto.setObjId(dynamicId.toString());
    		auto.setType(1);
    		auto.setTime(DateUtils.stringToDate("2024-08-12 18:52:32", "yyyy-MM-dd HH:mm:ss"));
    		userDynamicAutoMapper.insert(auto);
    	}
    	String key = "dynamic_auto0812";
    	redisUtil.set(key, auto.getObjId());
    	String timeKey = "dynamic_auto_time";
    	redisUtil.set(timeKey, DateUtils.dateToString(auto.getTime(), "yyyy-MM-dd HH:mm:ss"));
    	UserDynamic dynamic = new UserDynamic();
    	dynamic.setIsAutomatic(1);
    	dynamic.setId(dynamicId);
    	userDynamicService.updateById(dynamic);
		return AjaxResult.success(); 
	 }
}
